<template>
  <div class="app-container course course-list">
    <div class="filter-container">
      <div class="filter-block">
        <span>标题：</span>
        <el-input size="small" maxlength="30"  v-model="listQuery.title" @keyup.enter.native="fetchData(true) "/>
      </div>
      <div class="filter-block">
        <span>创建时间：</span>
        <!--<el-input size="small"  @keyup.enter.native="fetchData(true)"/>-->
        <el-date-picker
          :picker-options="pickerOptionsBeginTime"
          @change="changeCreateBeginTime"
          style="margin-right: 10px"
          size="small"
          v-model="listQuery.createBeginTime"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择">
        </el-date-picker>
        至
        <el-date-picker
          :picker-options="pickerOptionsEndTime"
          @change="changeCreateEndTime"
          size="small"
          style="margin-left: 10px"
          v-model="listQuery.createEndTime"
          type="date"
          value-format="yyyy-MM-dd 23:59:59"
          placeholder="请选择">
        </el-date-picker>
      </div>

      <div class="filter-block">
      <span>学科：</span>
      <el-select clearable size="small" v-model="listQuery.checkedSubject" clearable @change="fetchData(true)" >
        <el-option v-for="item in subjectList" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId"/>
      </el-select>
    </div>

      <div class="filter-block">
        <span>学期：</span>
        <el-select clearable size="small"  style="width: 220px" v-model="listQuery.checkedSemester"  @change="handleChangeSemester()" >
          <el-option v-for="item in schoolSemesterList"
                     :key="item.code"
                     :label="item.label"
                     :value="item.code"/>
        </el-select>
      </div>
      <div class="filter-block">
        <span>年级：</span>
        <el-select clearable size="small" v-model="listQuery.checkedGrade" @change="handleCheckedGrade" >
          <el-option v-for="item in gradeTypeData" :key="item.distanceYear" :label="item.name" :value="item.distanceYear"/>
        </el-select>
      </div>
      <div class="filter-btn-area">
        <el-button type="primary" size="small" @click="fetchData(true)">查询</el-button>
        <el-button type="none" size="small" @click="initListQuery">重置</el-button>
      </div>
      <div class="ope-btn-area">
        <template v-if="permissions.indexOf('pl:personfeedback:export') !== -1">
         <el-button size="primary" type="none" class="btn-none"  @click="exportFeedback" >导出</el-button>
        </template>
      </div>
    </div>
    <div class="calc-area" style="font-size: 14px;margin-bottom: 5px;color: #909399">
      共计 <span style="color: #02b2b5">{{pageInfo.total}}</span>条备课记录
    </div>

    <el-table ref="form" :data="tableData"  border show-overflow-tooltip style="width: 100%">
      <el-table-column
        label="序号" align="center"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column  label="学期" align="center">
        <template slot-scope="scope">
            <span  class="ellipsis2" :title=" formatSchoolYear(scope.row.schoolYear, scope.row.term)">
              {{ formatSchoolYear(scope.row.schoolYear, scope.row.term)}}
            </span>
        </template>
      </el-table-column>

      <el-table-column label="标题" prop="title" align="center" >
        <template slot-scope="scope">
          <span  class="ellipsis2" :title="scope.row.title">{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column label="反馈人" prop="createByName" align="center"/>
      <el-table-column label="反馈给谁" prop="title" align="center" >
        <template slot-scope="scope">
          <span  class="ellipsis2" :title="scope.row.feedbackTo">{{scope.row.feedbackTo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="年级" prop="gradeName" align="center"/>
      <el-table-column label="学科" prop="subjectName" align="center"/>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{scope.row.createAt | dataFormat }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        show-overflow-tooltip width="220" >
        <template slot-scope="scope">
          <div class="table-ope-btn-around">
            <el-link type="primary" :underline="false" @click="$router.push({path : '/pFeedBack/detail', query : {id : scope.row.id}})">查看</el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.pageNum"
      :page-sizes="[10, 30 ,50]"
      :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>

    <el-confirm-dialog
      elTip="确定要删除吗？"
      :showDialog="cancelConfirm"
      :confirmSubmit="elConfirmDialogSubmit"
      :confirmCancel="elConfirmDialogCancel"
      @closeDialog = "elConfirmDialogClose"
    >
    </el-confirm-dialog>
  </div>

</template>

<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import {getPersonCourseList, personFeedbackList,getSubjectList, getSchoolGradeList, getSchoolClassList, deletePlLesson, getSchoolSemesterList} from '@/api/api'
  import {mapGetters} from 'vuex'
  export default {
    name: "list",
    components: {
      ElConfirmDialog
    },
    computed: {
      ...mapGetters([
        'permissions','userInfo'
      ]),
    },
    data() {
      return {
        exportUrl : process.env.VUE_APP_BASE_API + "/feedback/exportPerson",
        schoolId : sessionStorage.getItem("schoolId"),
        //学科列表
        subjectList : [],
        //学期列表
        semesterList: [],
        schoolSemesterList : [],
        //年级列表
        gradeList: [],
        gradeTypeData : [],
        //班级列表
        classList: [],
        //查询列表
        courseList : [],
        pickerOptionsBeginTime: {
          // disabledDate(time) {
          //   return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
          // }
        },
        pickerOptionsEndTime: {
          // disabledDate(time) {
          //   return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
          // }
        },
        pageInfo: {
          pageNum: 1,
          pageSize: 10,
          total: 0
        },
        listQuery : {
          title: '',
          createBeginTime: null,
          createEndTime: null,
          checkedSubject: '',
          checkedSemester: '',
          checkedGrade: '',
          checkedClass: '',
          distanceYear : '',
          schoolYear : '',
          term : '',
          currentSemester: {
            semesterId : '',
            schoolYear : '',
            term: '',
          },
        },
        //班级下拉是否可以使用
        classDisabled : true,
        tableData: [],
        cancelConfirm: false,
        currentDeleteId: ''
      }
    },
    methods: {
      /** 查询相关 **/
      fetchData(initPageInfo) {
       if (initPageInfo) {
         this.pageInfo.pageNum = 1;
       }
        let params = {
          pageNum : this.pageInfo.pageNum,
          pageSize : this.pageInfo.pageSize,
          title : this.listQuery.title,
          createStartTime : this.listQuery.createBeginTime,
          createEndTime : this.listQuery.createEndTime,
          subjectId : this.listQuery.checkedSubject,
          classId : this.listQuery.checkedClass,
          distanceYear : this.listQuery.checkedGrade,
          schoolYear : this.listQuery.currentSemester.schoolYear,
          term : this.listQuery.currentSemester.term,
          grade : this.listQuery.checkedGrade,
        }
        personFeedbackList(params).then(res => {
          if (res.code === 200) {
            this.tableData = (res.result && Array.isArray(res.result.list)) ? res.result.list || [] : [];
            this.pageInfo.total = res.result.total || 0;
          } else {
            this.$alert("获取学生反馈数据失败！" + res.message, "错误", {type : "error"});
          }
        })
      },
      //重置查询
      initListQuery() {
        this.listQuery = {
          title: '',
          createBeginTime: null,
          createEndTime: null,
          checkedSubject: '',
          checkedSemester: '',
          checkedGrade: '',
          checkedClass: '',
          distanceYear : '',
          schoolYear : '',
          term : '',
          currentSemester: {
            semesterId : '',
            schoolYear : '',
            term: '',
          },
        }
        this.pickerOptionsEndTime = {
          disabledDate(time) {
            return null;
          }
        }
        this.pickerOptionsBeginTime = {
          disabledDate(time) {
            return null;
          }
        }
        this.fetchData(true)
      },

      changeCreateBeginTime() {
        let createBeginTime = this.listQuery.createBeginTime
        if (createBeginTime) {
          let beginTime =  new Date(createBeginTime.replace('-', '/'))
          this.pickerOptionsEndTime = {
            disabledDate(time) {
              return time.getTime() < beginTime  ;
            }
          }
        } else {
          this.pickerOptionsEndTime = {
            disabledDate(time) {
              return null ;
            }
          }
        }
      },
      changeCreateEndTime() {
        let createEndTime  = this.listQuery.createEndTime;
        if (createEndTime) {
          let endTime =   new Date(createEndTime.replace('-', '/'))
          this.pickerOptionsBeginTime = {
            disabledDate(time) {
              return time.getTime() > endTime ;
            }
          }
        } else {
          this.pickerOptionsBeginTime = {
            disabledDate(time) {
              return null ;
            }
          }
        }

      },
      //选择年级变化后 ，班级相应变化
      handleCheckedGrade() {
        let distanceYear = this.listQuery.checkedGrade;
        this.fetchData(true)
        // let tempGrade = this.getGradeMsgByDistanceYear(this.listQuery.checkedGrade);
        // if (tempGrade == null) {
        //   this.classList = []
        //   return ;
        // }
        // let params = {
        //   grade : tempGrade.name,
        //   distanceYear: tempGrade.distanceYear
        // }
        // getSchoolClassList(params).then(res => {
        //   if (res.code == 200) {
        //     this.classList = res.result || []
        //   } else {
        //     this.$alert('学校还未维护该年级下班级信息，请联系华育技术支持进行初始化！', '提示', {
        //       confirmButtonText: '我知道了',
        //     });
        //   }
        // })
      },

      //切换班级
      // handleCheckedClass(val) {
      //   if (val == true) {
      //     if (!this.listQuery.checkedGrade || this.classList.length == 0) {
      //       this.$message.warning({message: "请先选择年级！",duration:2000});
      //       return
      //     }
      //     this.fetchData(true)
      //   }
      // },
      /** 查询相关结束 **/
      /** 分页相关 **/
      // 格式化学年信息
      formatSchoolYear(schoolYear, schoolTerm) {
        let year = parseInt(schoolYear) + parseInt(1)
        let term = schoolTerm == 1 ? "第一学期" : "第二学期"
        return `${parseInt(schoolYear)}年-${year}年${term}`
      },
      handleSizeChange(val) {
        this.pageInfo.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageInfo.pageNum = val
        this.fetchData()
      },
      /** 分页相关结束**/

      /** 枚举格式化**/
      formatCourseType(code) {
        for (let item of this.courseList) {
          if (item.code === code ) {
            return item.label;
          }
        }
        return "";
      },

      /** 枚举格式化结束**/

      //点击取消按钮
      handleClickDelete(id) {
        if(!id) {
          return
        }
        this.currentDeleteId = id;
        this.cancelConfirm = true
      },
      /** 取消询问框相关**/
      elConfirmDialogSubmit() {
        this.initAddCourseForm()
        this.$router.push("/personal/courseList")
      },
      elConfirmDialogCancel() {
        this.cancelConfirm = false
      },
      elConfirmDialogClose() {
        this.cancelConfirm = false
      },
      /** 取消询问框相关结束**/
      /**  初始化 **/
      //初始化学科信息
      initSubjectList() {
        let params = {}
        getSubjectList(params).then(res => {
          if(res.code == 200) {
            this.subjectList = this.formatSubjectList(res.result)
          } else {
            this.$alert("获取学科数据失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      //格式化学科信息
      formatSubjectList(array) {
        if(!array || !Array.isArray(array) || array.length <= 0) {
          this.$alert('学校还未维护学科选项信息，请联系华育技术支持进行初始化！', '提示', {
            confirmButtonText: '我知道了',
          });
          return []
        }
        let tempArr = []
        array.forEach(item => {
          let tempItem = {
            subjectId: item.id,
            subjectName : item.name,
            subjectCode : item.code,
            subjectType : item.type,
            subjectLevel :  item.level
          }
          tempArr.push(tempItem)
        })
        return tempArr
      },
      //年级初始化
      initGradeList() {
        this.gradeTypeData= []
        getSchoolGradeList().then(res => {
          if (res.code === 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              this.gradeTypeData = res.result;
            } else {
              this.$alert('学校还未维护年级选项信息，请联系华育技术支持进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取年级选项列表失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      // 根据年级distanceYear获取年级详情
      getGradeMsgByDistanceYear(code) {
        if (this.gradeTypeData && this.gradeTypeData.length && this.gradeTypeData.length > 0) {
          for (let item of this.gradeTypeData) {
            if (item.distanceYear == code) {
              return item;
            }
          }
        }
        return null;
      },
      handleChangeSemester() {
        if (this.schoolSemesterList.length < 0){
          return null
        }
        for (let item of this.schoolSemesterList) {
          if (item.code == this.listQuery.checkedSemester) {
            if (item.code.length >= 5 ) {
              this.listQuery.currentSemester.semesterId = item.semesterId
              this.listQuery.currentSemester.schoolYear = item.code.substr(0, 4)
              this.listQuery.currentSemester.term = item.code.substr(4, 1)
            }
          }
        }
        this.fetchData(true)
      },
      initSchoolSemester() {
        getSchoolSemesterList().then(res => {
          if ( res.code == 200) {
            if (res.result && Array.isArray(res.result) && res.result.length > 0) {
              let tempSemesterList  = res.result
              tempSemesterList.forEach(semesterItem => {
                let year = parseInt(semesterItem.schoolYear) + parseInt(1)
                let term = semesterItem.term == 1 ? "第一学期" : "第二学期"
                let label   =  `${parseInt(semesterItem.schoolYear)}年-${year}年${term}`
                let code = `${semesterItem.schoolYear}${semesterItem.term}`
                let semesterId = semesterItem.id
                this.schoolSemesterList.push({label, code, semesterId})
                this.schoolSemesterList.sort(this.compare('code'))

              })
            } else {
              this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
          }
        })

      },
      // 导出我的反馈
      exportFeedback() {
        let url = this.exportUrl + "?schoolToken=" + this.schoolId + "&title=" + this.listQuery.title
          + "&createStartTime=" +this.listQuery.createBeginTime + "&createEndTime=" + this.listQuery.createEndTime
          + "&subjectId=" + this.listQuery.checkedSubject + "&classId=" + this.listQuery.checkedClass
          +  "&distanceYear=" + this.listQuery.checkedGrade + "&schoolYear=" + this.listQuery.currentSemester.schoolYear
          +  "&term=" + this.listQuery.currentSemester.term + "&grade=" + this.listQuery.checkedGrade;
        window.open(url);
      },
      compare (propertyName) {
        return function (object1, object2) {
          let value1 = object1[propertyName]
          let value2 = object2[propertyName]
          if (value2 > value1) {
            return 1
          } else if (value2 < value1) {
            return -1
          } else {
            return 0
          }
        }
      }

      /**  初始化结束 **/


    },
    mounted () {
      this.initSubjectList()
      this.initGradeList()
      this.initSchoolSemester()

    },
    created() {
      this.fetchData(true)

    },
  }
</script>

<style scoped>

</style>
